package com.chukun.spring.bean.lifecycle;

import com.chunkun.ioc.domain.User;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor;

/**
 *  bean的生命周期相关的操作
 * @author chukun
 */
public class BeanLifecycleDemo {

    public static void main(String[] args) {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        // 添加 BeanPostProcessor 实现 BeanLifecycleInstantiationAwareBeanPostProcessor
        beanFactory.addBeanPostProcessor(new BeanLifecycleInstantiationAwareBeanPostProcessor());
        // 添加 DestructionAwareBeanPostProcessor 实现 BeanLifecycleDestructionAwareBeanPostProcessor
        beanFactory.addBeanPostProcessor(new BeanLifecycleDestructionAwareBeanPostProcessor());
        // 添加 CommonAnnotationBeanPostProcessor 解决 @PostConstruct @PreDestroy
        beanFactory.addBeanPostProcessor(new CommonAnnotationBeanPostProcessor());
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
        String [] locations  = {"/META-INF/dependency-lookup-context.xml","/META-INF/bean-constructor-dependency-injection.xml"};
        int beanNumbers = reader.loadBeanDefinitions(locations);
        System.out.println("已加载 BeanDefinition 数量：" + beanNumbers);
        // 显示地执行 preInstantiateSingletons()
        // SmartInitializingSingleton 通常在 Spring ApplicationContext 场景使用
        // preInstantiateSingletons 将已注册的 BeanDefinition 初始化成 Spring Bean
        beanFactory.preInstantiateSingletons();
        // 通过 Bean Id 和类型进行依赖查找
        User user = beanFactory.getBean("user", User.class);
        System.out.println(user);

        User superUser = beanFactory.getBean("superUser", User.class);
        System.out.println(superUser);

        // 构造器注入按照类型注入，resolveDependency
        UserHolder userHolder = beanFactory.getBean("userHolder", UserHolder.class);

        // 销毁userHolder
        // 执行 Bean 销毁（容器内）
        beanFactory.destroyBean("userHolder", userHolder);

        System.out.println(userHolder);


    }
}
